package com.richapp.launcher.serialport.infrared;

import android.util.Log;


import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.serialport.infrared.interfaces.IMessage;
import com.richapp.launcher.serialport.infrared.interfaces.InfraredMessageListener;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by jack on 2015/4/2 0002.
 */
public class InfraredRunThread implements Runnable {

    private static final String TAG = InfraredRunThread.class.getName();
    private ConcurrentLinkedQueue<IMessage> messageList;

    private boolean runFlag = false;
    private IMessage lastIMessage = null;


    public InfraredRunThread(){
        messageList = new ConcurrentLinkedQueue<IMessage>();
    }

    @Override
    public void run() {
        while (runFlag){
            try {
                if(lastIMessage == null){
                    if(messageList.size() > 0){
                        Log.d(TAG,"发送红外消息");
                        IMessage iMessage = messageList.poll();
                        if(iMessage != null){
                            lastIMessage = iMessage;
                            iMessage.doCheckData();
                            iMessage.doSendData();

                            //
                            GPIOServer.getInstance().lightFlash();
                        }
                    }
                }else{
                    if(lastIMessage.isResultOk() || lastIMessage.isTimeOut()){
                        lastIMessage = null;
                    }else{
                        lastIMessage.doGetResult();
                    }
                }
                Thread.sleep(100);
            }catch (Exception e){
                Log.d(TAG,"红外错误:"+e.getMessage());
            }
        }
    }

    public boolean isRunFlag() {
        return runFlag;
    }

    public void setRunFlag(boolean runFlag) {
        this.runFlag = runFlag;
    }

    public void addMessage(IMessage iMessage){
        messageList.add(iMessage);
    }
}
